package deyi.http;

import deyi.cache.AppCache;
import deyi.log.AppLogger;
import deyi.utils.AppConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component("httpposter")
@Scope("prototype")
@Data
public class HttpPoster{

    private String url;
    private String content;
    private String postLog;
    @Autowired
    private AppConfig appConfig;
    @Autowired
    private AppCache appCache;

    public void postJson(){
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(appConfig.getHttpConnectTime(), TimeUnit.SECONDS).readTimeout(appConfig.getHttpReadTime(),TimeUnit.SECONDS).build();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),content);
        Request request = new Request.Builder().post(requestBody).url(url).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                AppLogger.logInfo("middle post data to FS failed " + " [post data]: " + postLog);
                appCache.getPushFailedList().addObj(content);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                AppLogger.logInfo("middle post data to FS success " + " [post data]: "  + postLog);
            }
        });
    }

}
